package com.itheima.sfbx.insurance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.EmptyUtil;
import com.itheima.sfbx.framework.commons.utils.ExceptionsUtil;
import com.itheima.sfbx.insurance.constant.CategoryCacheConstant;
import com.itheima.sfbx.insurance.constant.SafeguardCacheConstant;
import com.itheima.sfbx.insurance.dto.SafeguardVO;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.insurance.mapper.SafeguardMapper;
import com.itheima.sfbx.insurance.pojo.Safeguard;
import com.itheima.sfbx.insurance.service.ISafeguardService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 保障项服务实现类
 */
@Slf4j
@Service
public class SafeguardServiceImpl extends ServiceImpl<SafeguardMapper, Safeguard> implements ISafeguardService  {
    /**
     * 多条件查询保障项分页
     * @param safeguardVO 保障项查询条件
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @return Page<SafeguardVO>
     */
    @Override
    @Cacheable(value = SafeguardCacheConstant.PAGE,key ="#pageNum+'-'+#pageSize+'-'+#safeguardVO.hashCode()")
    public Page<SafeguardVO> findPage(SafeguardVO safeguardVO, int pageNum, int pageSize) {
        try {
            // 构造查询条件
            LambdaQueryWrapper<Safeguard> lambdaQueryWrapper = getSafeguardLambdaQueryWrapper(safeguardVO);
            // 分页查询
            Page<Safeguard> page = new Page<>(pageNum, pageSize);
            Page<Safeguard> safeguardPage = page(page, lambdaQueryWrapper);
            // 返回结果
            return BeanConv.toPage(safeguardPage,SafeguardVO.class);
        } catch (Exception e) {
            log.error("查询保障项分页失败:{}",ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.PAGE_FAIL);
        }
    }

    @NotNull
    private static LambdaQueryWrapper<Safeguard> getSafeguardLambdaQueryWrapper(SafeguardVO safeguardVO) {
        // 构造查询条件
        LambdaQueryWrapper<Safeguard> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 根据SafeguardKeyName模糊查询，如果输入不为空
        lambdaQueryWrapper.like(!EmptyUtil.isNullOrEmpty(safeguardVO.getSafeguardKeyName()),
                Safeguard::getSafeguardKeyName, safeguardVO.getSafeguardKeyName());
        // 根据SafeguardKey精确查询，如果输入不为空
        lambdaQueryWrapper.eq(!EmptyUtil.isNullOrEmpty(safeguardVO.getSafeguardKey()),
                Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey());
        // 根据DataState精确查询，如果输入不为空
        lambdaQueryWrapper.eq(!EmptyUtil.isNullOrEmpty(safeguardVO.getDataState()),
                Safeguard::getDataState, safeguardVO.getDataState());
        // 按创建时间降序排列
        lambdaQueryWrapper.orderByDesc(Safeguard::getCreateTime);
        return lambdaQueryWrapper;
    }

    @Override
    public SafeguardVO findById(String safeguardId) {
        try {
            //执行查询
            //返回结果
            return BeanConv.toBean(getById(safeguardId),SafeguardVO.class);
        } catch (Exception e) {
            log.error("查询保障项失败:{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.FIND_ONE_FAIL);
        }
    }

    /**
     * 保障项保存
     * @param safeguardVO 保障项VO对象
     * @return SafeguardVO
     */
    @Override
    @Caching(
            evict = {
                    @CacheEvict(value = SafeguardCacheConstant.PAGE,allEntries = true),
                    @CacheEvict(value = SafeguardCacheConstant.LIST,allEntries = true)},
            put={
                    @CachePut(value =SafeguardCacheConstant.BASIC,key = "#result.id")
            })
    public SafeguardVO save(SafeguardVO safeguardVO) {
        try {
            //  转换VO对象为实体对象,通过mp进行保存
            Safeguard safeguard = BeanConv.toBean(safeguardVO,Safeguard.class);
            //调用mp的方法进行保存
            boolean flag = save(safeguard);
            //判断是否保存成功
            if (!flag){
                throw new RuntimeException("保存失败");
            }
            //返回结果
            return BeanConv.toBean(safeguard,SafeguardVO.class);
        } catch (RuntimeException e) {
            log.error("保存失败:{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }
    }

    /**
     * 保障项修改
     * @param safeguardVO 保障项VO对象
     * @return Boolean
     */
    @Override
    @Caching(evict = {@CacheEvict(value = SafeguardCacheConstant.PAGE,allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.LIST,allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.BASIC,key = "#safeguardVO.id")})
    public Boolean update(SafeguardVO safeguardVO) {
        try {
            //把vo转换为对应表的对象方便mp进行操作
            Safeguard safeguard = BeanConv.toBean(safeguardVO,Safeguard.class);
            //调用mp进行修改
            //返回结果
            return updateById(safeguard);
        } catch (Exception e) {
            log.error("修改失败:{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
    }

    /**
     * 批量删除
     * @param checkedIds 批量删除的id
     * @return Boolean
     */
    @Override
    @Caching(evict = {@CacheEvict(value = SafeguardCacheConstant.PAGE,allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.LIST,allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.BASIC,allEntries = true)})
    public Boolean delete(String[] checkedIds) {
        try {
            //根基传递的数据id通过mp进行批量删除
            return removeByIds(Arrays.asList(checkedIds));
        } catch (Exception e) {
            log.error("批量删除失败:{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.DEL_FAIL);
        }
    }

    @Override
    @Cacheable(value = SafeguardCacheConstant.LIST,key ="#safeguardVO.hashCode()")
    public List<SafeguardVO> findList(SafeguardVO safeguardVO) {
        try {
            //构建查询条件
            LambdaQueryWrapper<Safeguard> lambdaQueryWrapper = getSafeguardLambdaQueryWrapper(safeguardVO);
            //查询
            List<Safeguard> list = list(lambdaQueryWrapper);
            //转换为VO对象并返回
            return BeanConv.toBeanList(list,SafeguardVO.class);
        } catch (Exception e) {
            log.error("查询失败:{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.PAGE_FAIL);
        }
    }

    @Override
    public List<SafeguardVO> findShowPageItemByKey(List<String> safeguardKeyList) {
        return List.of();
    }

    @Override
    public SafeguardVO findBySafeguardKey(String safeguardKey) {
        return null;
    }
}
